/**
 * 解析 GitHub 仓库 URL，提取 owner、repo、branch 和文件路径
 * 支持格式：
 *   - https://github.com/owner/repo
 *   - https://github.com/owner/repo/tree/branch/path
 *   - https://github.com/owner/repo/blob/branch/path/to/file
 *   - https://github.com/owner/repo/tree/tag-name
 *   - https://github.com/owner/repo/tree/commit-hash
 * 
 * owner: 仓库所有者（用户或组织名），如 facebook
   repo: 仓库名称，如 react
 * 如：https://github.com/facebook/react/tree/v18.2.0
 *
 * @param {string} url - GitHub 仓库 URL
 * @returns {Object} { owner, repo, branch, filePath, type }
 * @throws {Error} 如果 URL 格式不合法或无法解析
 */
function parseGithubUrl(url) {
    try {
        const parsedUrl = new URL(url);

        // 确保是 github.com
        if (parsedUrl.hostname !== 'github.com') {
            throw new Error('Only github.com URLs are supported');
        }

        // 获取路径并去除空字符串
        const parts = parsedUrl.pathname.split('/').filter(Boolean);

        // 至少需要 owner 和 repo 两段
        if (parts.length < 2) {
            throw new Error('Invalid GitHub repository URL: insufficient path segments');
        }

        const owner = parts[0];
        const repo = parts[1];

        // 默认分支和路径
        let branch = 'main'; // 默认值，后面会尝试获取
        let filePath = '';
        let type = 'repo'; // repo, tree, blob

        // 处理后续路径
        if (parts.length > 2) {
            const mode = parts[2]; // tree, blob, etc.

            if (mode === 'tree' || mode === 'blob') {
                type = mode;
                if (parts.length > 3) {
                    branch = decodeURIComponent(parts[3]); // 分支/标签/提交哈希

                    // 剩余部分作为文件路径
                    if (parts.length > 4) {
                        filePath = parts.slice(4).join('/');
                    }
                }
            }
        }

        return {
            owner,
            repo,
            branch,
            filePath,
            type,
            originalPath: parsedUrl.pathname
        };
    } catch (error) {
        if (error instanceof TypeError) {
            throw new Error('Invalid URL: malformed or missing');
        }
        throw error;
    }
}

/**
 * 获取默认分支（避免硬编码 main/master）
 */
async function getDefaultBranch(owner, repo) {
    try {
        const url = `https://api.github.com/repos/${owner}/${repo}`;
        const response = await fetch(url);

        if (!response.ok) {
            throw new Error(`GitHub API error: ${response.status} ${response.statusText}`);
        }

        const info = await response.json();
        return info.default_branch || 'main';
    } catch (error) {
        console.warn('Failed to get default branch, using "main" as fallback:', error.message);
        return 'main'; // 回退值
    }
}

/**
 * 构建 package.json 的 raw 链接
 */
async function getPackageJsonUrl(githubInfo) {
    const { owner, repo, branch, filePath } = githubInfo;

    // 确定要使用的分支/引用
    let ref = branch;

    // 如果 URL 中没有指定分支，获取默认分支
    if (!ref || ref === 'main' || ref === 'master') {
        ref = await getDefaultBranch(owner, repo);
    }

    // 如果原始路径中有文件路径，尝试在该路径下查找 package.json
    // 否则在根目录查找
    const targetPath = filePath
        ? `${filePath}/package.json`
        : 'package.json';

    return `https://raw.githubusercontent.com/${owner}/${repo}/${ref}/${targetPath}`;
}

/**
 * 解析远程项目并获取 package.json
 */
export async function parseRemoteProject(githubUrl) {
    try {
        const gitInfo = parseGithubUrl(githubUrl);
        const packageJsonUrl = await getPackageJsonUrl(gitInfo);

        const response = await fetch(packageJsonUrl);

        if (!response.ok) {
            throw new Error(`Failed to fetch package.json: ${response.status} ${response.statusText}`);
        }

        const packageJson = await response.json();
        return packageJson;

    } catch (error) {
        console.error('Error parsing remote project:', error);
        throw new Error(`Failed to parse remote project: ${error.message}`);
    }
}

// 使用示例
// parseRemoteProject('https://github.com/facebook/react/tree/v18.2.0')
//   .then(pkg => console.log(pkg))
//   .catch(err => console.error(err));

// 各种 GitHub URL 格式都能处理
// const urls = [
//   'https://github.com/facebook/react',
//   'https://github.com/facebook/react/tree/main',
//   'https://github.com/facebook/react/tree/v18.2.0',
//   'https://github.com/facebook/react/blob/main/package.json',
//   'https://github.com/vuejs/vue/tree/dev/packages/compiler-sfc'
// ];

// // 获取所有 package.json
// urls.forEach(async (url) => {
//   try {
//     const pkg = await getPackageJsonFromGithub(url);
//     console.log(`${url} -> ${pkg.name}@${pkg.version}`);
//   } catch (error) {
//     console.error(`Failed for ${url}:`, error.message);
//   }
// });